<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" class="form-container">

      <sticky v-if="isAudit&&postForm.status==0" :z-index="1501" :class-name="'sub-navbar ' + statusClass">
        <el-button v-loading="loading" style="margin-left: 10px;" type="warning" @click="check">
          敏感词检索
        </el-button>
        <el-button type="danger" @click="reject">
          驳回帖子
        </el-button>
        <el-button type="success" @click="pass">
          通过审核
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="postForm.title" :maxlength="100" name="name" readonly>
                标题
              </MDinput>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <el-col :span="6">
                  <el-form-item label-width="47px" label="作者:" class="postInfo-container-item">
                    <el-input v-model="postForm.user.name"></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="120px" label="发布时间:" class="postInfo-container-item">
                    <el-date-picker v-model="creatTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" readonly />
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="120px" label="修改时间:" class="postInfo-container-item">
                    <el-date-picker v-model="modifyTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" readonly />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item style="margin-bottom: 40px;" label-width="47px" label="标签:">
          <el-tag v-for="(item,index) in splitTags" :key="item+index" :type="getTagType()" style="margin-right: 10px;" effect="plain">{{item}}</el-tag>
          <hr style="background-color:#E0E0E0; border:none;height: 1px;"/>
          <span v-show="tagCount" class="word-counter">{{ tagCount }}个标签</span>
        </el-form-item>

        <el-form-item style="margin-bottom: 30px;" label="内容:" >
          <br/>
          <mavon-editor
            class="md"
            :value="postForm.description"
            :subfield = "false"
            :defaultOpen = "'preview'"
            :toolbarsFlag = "false"
            :editable="false"
            :scrollStyle="true"
            :ishljs = "true"
          ></mavon-editor>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import { fetchPost } from '@/api/post'
import { retrieveSensitiveWord } from '@/api/post'
import { pass } from '@/api/post'
import { reject } from '@/api/post'

const defaultForm = {
  id: undefined, // 文章ID
  title: 'mysql8.0的连接URL', // 文章题目
  description: '#### mysql8.0的连接URL\n' +
    '> jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false',
  tags: 'java,mysql', // 文章摘要
  gmtCreate: 1586451826050, // 文章发布时间
  gmtModify: 1586821362390, // 文章修改时间
  user: { name: 'liuhao' }
}

export default {
  name: 'ArticleDetail',
  components: { MDinput, Sticky },
  props: {
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      tempRoute: {}
    }
  },
  // 计算属性
  computed: {
    statusClass() {
      if (this.postForm.gmtCreate === this.postForm.gmtModify) {
        return 'draft'
      } else {
        return 'published'
      }
    },
    // 计算标签的数量
    tagCount() {
      var array = this.postForm.tags.split(/,|，/)
      return array.length
    },
    // 获取标签数组
    splitTags() {
      var array = this.postForm.tags.split(/,|，/)
      return array
    },
    // 获取帖子的创建时间
    creatTime: {
      get() {
        return (new Date(this.postForm.gmtCreate))
      },
      set(val) {
        this.postForm.gmtCreate = new Date(val)
      }
    },
    // 获取帖子的修改时间
    modifyTime: {
      get() {
        return (new Date(this.postForm.gmtModify))
      },
      set(val) {
        this.postForm.gmtModify = new Date(val)
      }
    }
  },
  created() {
    // 获取帖子ID
    const id = this.$route.params && this.$route.params.id
    // 根据帖子ID获取帖子
    this.fetchData(id)

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    // 查询帖子相关信息
    fetchData(id) {
      fetchPost(id).then(response => {
        this.postForm = Object.assign(this.postForm, response.data.post)

        // set tagsview title
        this.setTagsViewTitle()
        // set page title
        this.setPageTitle()
      }).catch(err => {
        console.log(err)
      })
    },
    // 设置页面标签的信息
    setTagsViewTitle() {
      const title = '帖子审核'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    // 设置当前页面的tittle1
    setPageTitle() {
      const title = '帖子审核'
      document.title = `${title}-${this.postForm.title}`
    },
    // 敏感词汇检测
    check() {
      const id = this.$route.params && this.$route.params.id
      if (this.postForm.description.length === 0 || this.postForm.title.length === 0) {
        this.$message({
          message: '该帖子信息不完整!',
          type: 'warning'
        })
        return
      } else {
        retrieveSensitiveWord(id).then(response => {
          let message = ''
          const sensitiveWord = response.data.sensitive
          if (this.isEmpty(sensitiveWord)) {
            message = '没有检索到敏感词汇,可以通过审核'
          } else {
            message = this.sensitiveWordSplic(sensitiveWord)
          }
          this.$alert(message, '检索结果', {
            confirmButtonText: '确定',
            dangerouslyUseHTMLString: true
          })
        }).catch(err => {
          console.log(err)
        })
      }
    },
    isEmpty(obj) {
      for (var key in obj) {
        return false
      }
      return true
    },
    sensitiveWordSplic(ary) {
      const prefix = '该帖中包含敏感词汇：'
      const suffix = '，不应通过审核!'
      var arr = Object.keys(ary)
      let result = ''
      for (let i in ary) {
        if (i == arr.length - 1) {
          result += '<font color=red >' + ary[i] + '</font>'
        } else {
          result += ('<font color=red >' + ary[i] + '</font>') + '，'
        }
      }
      return prefix + result + suffix
    },
    reject() {
      this.$confirm('确认驳回此贴吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true

        // 驳回此贴
        reject(this.postForm.id).then(response => {
          const status = response.data.result
          if (status) {
            this.$notify({
              title: '成功',
              message: '该帖驳回成功',
              type: 'success',
              duration: 2000
            })
            this.$router.push('/post/auditPost')
          } else {
            this.$notify({
              title: '失败',
              message: '该帖驳回失败',
              type: 'error',
              duration: 2000
            })
          }
        }).catch(err => {
          console.log(err)
        })
        this.loading = false
      }).catch(() => {
        this.$notify({
          title: '取消',
          message: '已取消驳回',
          type: 'info',
          duration: 2000
        })
      })
    },
    // 通过审核
    pass() {
      this.$confirm('确认审核通过此贴吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true

        // 审核通过此贴
        pass(this.postForm.id).then(response => {
          const status = response.data.result
          if (status) {
            this.$notify({
              title: '成功',
              message: '帖子通过审核',
              type: 'success',
              duration: 2000
            })
            this.$router.push('/post/auditPost')
          } else {
            this.$notify({
              title: '失败',
              message: '帖子通过审核失败',
              type: 'error',
              duration: 2000
            })
          }
        }).catch(err => {
          console.log(err)
        })

        this.loading = false
      }).catch(() => {
        this.$notify({
          title: '取消',
          message: '已取消通过审核',
          type: 'info',
          duration: 2000
        })
      })
    },
    getTagType() {
      const random = Math.floor(Math.random() * 5)
      switch (random) {
        case 1:
          return 'success'
        case 2:
          return 'info'
        case 3:
          return 'warning'
        case 4:
          return 'danger'
        default:
          return ''
      }
    }
  }
}
</script>

<style lang="scss" >
  @import "~@/styles/mixin.scss";

  .createPost-container {
    position: relative;

    .createPost-main-container {
      padding: 0px 45px 20px 50px;

      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;

        .postInfo-container-item {
          float: left;
        }
      }
    }

    .word-counter {
      width: 60px;
      position: absolute;
      right:20px;
      top: 0px;
    }
  }

  .article-textarea /deep/ {
    textarea {
      padding-right: 40px;
      resize: none;
      border: none;
      border-radius: 0px;
      border-bottom: 1px solid #bfcbd9;
    }
  }
</style>
